package com.example.demo7

import android.Manifest
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity() {
    
    private var musicService: MusicService? = null
    private var isBound = false
    
    private lateinit var btnPlay: Button
    private lateinit var btnPause: Button
    private lateinit var btnStop: Button
    private lateinit var btnNext: Button
    private lateinit var btnPrev: Button
    private lateinit var seekBar: SeekBar
    private lateinit var tvSongName: TextView
    private lateinit var tvSongInfo: TextView
    
    private val handler = Handler(Looper.getMainLooper())
    private var isUserSeeking = false
    
    // 更新进度的Runnable
    private val updateProgressRunnable = object : Runnable {
        override fun run() {
            musicService?.let { service ->
                if (!isUserSeeking && service.isPlaying()) {
                    val currentPosition = service.getCurrentPosition()
                    val duration = service.getDuration()
                    
                    if (duration > 0) {
                        seekBar.max = duration
                        seekBar.progress = currentPosition
                    }
                }
                
                // 更新歌曲信息
                tvSongName.text = service.getCurrentSongName()
                tvSongInfo.text = "${service.getCurrentIndex() + 1}/${service.getMusicListSize()}"
            }
            handler.postDelayed(this, 500) // 每500ms更新一次
        }
    }
    
    // 权限请求
    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        if (isGranted) {
            bindMusicService()
        } else {
            Toast.makeText(this, "需要读取音频文件权限", Toast.LENGTH_SHORT).show()
        }
    }
    
    // Service连接
    private val connection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val binder = service as MusicService.MusicBinder
            musicService = binder.getService()
            isBound = true
            
            // 重新加载音乐列表
            musicService?.reloadMusicList()
            
            // 开始更新进度
            handler.post(updateProgressRunnable)
            
            Toast.makeText(this@MainActivity, "正在扫描音乐文件...", Toast.LENGTH_SHORT).show()
            
            // 延迟3秒后再显示音乐数量（等待扫描完成）
            handler.postDelayed({
                val musicCount = musicService?.getMusicListSize() ?: 0
                Toast.makeText(this@MainActivity, "找到 $musicCount 首歌曲", Toast.LENGTH_LONG).show()
            }, 3000)
        }
        
        override fun onServiceDisconnected(name: ComponentName?) {
            musicService = null
            isBound = false
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        initViews()
        setupListeners()
        checkPermissionAndBindService()
    }
    
    private fun initViews() {
        btnPlay = findViewById(R.id.btnPlay)
        btnPause = findViewById(R.id.btnPause)
        btnStop = findViewById(R.id.btnStop)
        btnNext = findViewById(R.id.btnNext)
        btnPrev = findViewById(R.id.btnPrev)
        seekBar = findViewById(R.id.seekBar)
        tvSongName = findViewById(R.id.tvSongName)
        tvSongInfo = findViewById(R.id.tvSongInfo)
    }
    
    private fun setupListeners() {
        btnPlay.setOnClickListener {
            musicService?.play()
        }
        
        btnPause.setOnClickListener {
            musicService?.pause()
        }
        
        btnStop.setOnClickListener {
            musicService?.stop()
        }
        
        btnNext.setOnClickListener {
            musicService?.next()
        }
        
        btnPrev.setOnClickListener {
            musicService?.previous()
        }
        
        // SeekBar拖动监听
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                // 进度改变时
            }
            
            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                isUserSeeking = true
            }
            
            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                isUserSeeking = false
                seekBar?.progress?.let { progress ->
                    musicService?.seekTo(progress)
                }
            }
        })
    }
    
    private fun checkPermissionAndBindService() {
        val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            Manifest.permission.READ_MEDIA_AUDIO
        } else {
            Manifest.permission.READ_EXTERNAL_STORAGE
        }
        
        when {
            ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED -> {
                bindMusicService()
            }
            else -> {
                requestPermissionLauncher.launch(permission)
            }
        }
    }
    
    private fun bindMusicService() {
        val intent = Intent(this, MusicService::class.java)
        startService(intent)
        bindService(intent, connection, Context.BIND_AUTO_CREATE)
    }
    
    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacks(updateProgressRunnable)
        if (isBound) {
            unbindService(connection)
            isBound = false
        }
    }
}